package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type ErpEntry struct {
	Id                 int64
	DepartmentId       int64
	Suppliers          *ErpSuppliers `orm:"rel(fk);null;on_delete(do_nothing)"`
	Number             string
	Auditing           int     //审核状态0待审，1通过,2驳回,3已冲红,4已入库
	Money              float64 //总金额
	Postage            float64 //邮费
	ProNumber          int64   //产品数量
	PayMethod          int
	DeliveryMode       int
	Remarks            string
	CreatedAt          int64
	UpdatedAt          int64
	CreatedBy          string
	UpdatedBy          string
	ErpEntryData       []*ErpEntryData `orm:"reverse(many)"`
	Reconciliation     int    //对帐状态2未对，1通过
	ReconciliationUser string //对帐人
	ReconciliationDate string //对帐时间
	IsTemp             int
	StorageNum         int64
	AcceptanceCheck    int64             //待验收数量
	TotalTaxPrice      float64 `orm:"-"` //总税额
	TotalDiscountPrice float64 `orm:"-"` //总折扣额
	TotalPreTax        float64 `orm:"-"` //总税前
	TotalTaxAfter      float64 `orm:"-"` //总税后
}

//查询
type ErpEntryQueryParam struct {
	BaseQueryParam
	Filter        string
	Auditing      int
	DepartmentId  int64
	IsAcceptance  bool
}

func (a *ErpEntry) TableName() string {
	return ErpEntryTableName()
}

func ErpEntryTableName() string {
	return TableName("erp_entry")
}

func ErpEntryPageList(params *ErpEntryQueryParam) ([]*ErpEntry, int64) {

	ls := make([]*ErpEntry, 0)

	query := orm.NewOrm().QueryTable(ErpEntryTableName()).RelatedSel("Suppliers")

	if len(params.Filter) > 0 {
		query = query.Filter("number__istartswith", params.Filter)
	}

	if params.Auditing > 0 {
		query = query.Filter("auditing", params.Auditing)
	}

	if params.IsAcceptance == true {
		query = query.Filter("AcceptanceCheck__gt", 0)
	}
	if params.DepartmentId > 0 {
		query = query.Filter("department_id", params.DepartmentId)
	}
	query = query.Filter("is_temp", 0)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func GetErpEntryById(id int64) (*ErpEntry, error) {

	r := new(ErpEntry)
	err := orm.NewOrm().QueryTable(ErpEntryTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func ErpEntryAdd(c *ErpEntry) (int64, error) {

	return orm.NewOrm().Insert(c)
}

func (a *ErpEntry) ErpEntryEdit(filter ...string) error {

	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

//按时间段
func QueryEntryTimeSoltSeterCount(starttime, endtime int64) int64 {
	count, _ := queryEntryTimeSoltSeter(starttime, endtime).Count()
	return count
}

func queryEntryTimeSoltSeter(starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(ErpEntryTableName())

	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	cond = cond.And("is_temp", 0)
	query = query.SetCond(cond)

	return query
}
